const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const axios = require('axios');

exports.getList = async (req, res, next) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 6;
    const category = req.query.category || '';
    const keyword = req.query.keyword || '';
    const offset = (page - 1) * pageSize;

    let whereClause = [];
    let params = [];

    if (category) {
      whereClause.push('category = ?');
      params.push(category);
    }

    if (keyword) {
      whereClause.push('(name LIKE ? OR author LIKE ? OR isbn LIKE ? OR publisher LIKE ?)');
      const likeKeyword = `%${keyword}%`;
      params.push(likeKeyword, likeKeyword, likeKeyword, likeKeyword);
    }

    const where = whereClause.length > 0 ? 'WHERE ' + whereClause.join(' AND ') : '';

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM books ${where}`;
    const [countResult] = await pool.query(countSql, params);
    const total = countResult[0].total;

    // 查询数据
    const sql = `SELECT * FROM books ${where} ORDER BY id DESC LIMIT ?, ?`;
    const dataParams = [...params, offset, pageSize];
    const [books] = await pool.query(sql, dataParams);

    success(res, {
      list: books,
      total: total,
      hasMore: (page * pageSize) < total,
      pagination: { page, pageSize, total: total }
    });
  } catch (err) {
    console.error('获取图书列表失败:', err);
    next(err);
  }
};

exports.getDetail = async (req, res, next) => {
  try {
    const { id } = req.params;
    const [books] = await pool.query('SELECT * FROM books WHERE id = ?', [id]);

    if (books.length === 0) {
      return error(res, '图书不存在', 404);
    }

    success(res, books[0]);
  } catch (err) {
    next(err);
  }
};

// 获取图书分类列表
exports.getCategories = async (req, res, next) => {
  try {
    const [categories] = await pool.query(
      'SELECT category, COUNT(*) as count FROM books WHERE category IS NOT NULL AND category != "" GROUP BY category ORDER BY count DESC'
    );

    success(res, categories.map(item => ({
      name: item.category,
      count: item.count
    })));
  } catch (err) {
    console.error('获取分类列表失败:', err);
    next(err);
  }
};

exports.create = async (req, res, next) => {
  try {
    const {
      isbn, name, author, translator, publisher, publish_date,
      category, category_id, cover, price, pages, binding,
      summary, author_intro, catalog, stock, rating, rating_count,
      douban_id, data_source
    } = req.body;

    // 验证必填字段
    if (!name || name.trim() === '') {
      return res.status(400).send({
        code: 400,
        message: '书名不能为空'
      });
    }

    const [result] = await pool.query(
      `INSERT INTO books (isbn, name, author, translator, publisher, publish_date,
       category, category_id, cover, price, pages, binding, summary, author_intro,
       catalog, stock, rating, rating_count, douban_id, data_source)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        isbn || null,
        name.trim(),
        author || null,
        translator || null,
        publisher || null,
        publish_date || null,
        category || null,
        category_id || 1,
        cover || null,
        price || null,
        pages || null,
        binding || null,
        summary || null,
        author_intro || null,
        catalog || null,
        stock || 0,
        rating || null,
        rating_count || 0,
        douban_id || null,
        data_source || 'manual'
      ]
    );

    // 获取新创建的书籍信息
    const [newBooks] = await pool.query('SELECT * FROM books WHERE id = ?', [result.insertId]);

    res.status(201).send({
      code: 201,
      data: newBooks[0],
      message: '添加书籍成功'
    });
  } catch (err) {
    console.error('创建图书失败:', err);
    next(err);
  }
};

exports.update = async (req, res, next) => {
  try {
    const { id } = req.params;
    const allowedFields = [
      'isbn', 'name', 'author', 'translator', 'publisher', 'publish_date',
      'category', 'category_id', 'cover', 'price', 'pages', 'binding',
      'summary', 'author_intro', 'catalog', 'stock', 'rating', 'rating_count',
      'douban_id', 'data_source'
    ];
    
    // 构建动态更新SQL
    const updateFields = [];
    const updateValues = [];
    
    allowedFields.forEach(field => {
      if (req.body[field] !== undefined) {
        updateFields.push(`${field} = ?`);
        updateValues.push(req.body[field]);
      }
    });
    
    if (updateFields.length === 0) {
      return error(res, '没有要更新的字段', 400);
    }
    
    updateValues.push(id);
    const sql = `UPDATE books SET ${updateFields.join(', ')} WHERE id = ?`;
    
    const [result] = await pool.query(sql, updateValues);
    
    if (result.affectedRows === 0) {
      return error(res, '书籍不存在', 404);
    }
    
    // 获取更新后的书籍信息
    const [updatedBooks] = await pool.query('SELECT * FROM books WHERE id = ?', [id]);
    
    success(res, updatedBooks[0], '更新成功');
  } catch (err) {
    next(err);
  }
};

exports.delete = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    const [result] = await pool.query('DELETE FROM books WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return error(res, '书籍不存在', 404);
    }
    
    success(res, null, '删除成功');
  } catch (err) {
    next(err);
  }
};

/**
 * 搜索豆瓣图书
 */
exports.searchDouban = async (req, res, next) => {
  try {
    const { keyword, count = 10 } = req.query;
    
    if (!keyword) {
      return error(res, '请输入搜索关键词', 400);
    }

    console.log('正在搜索豆瓣图书:', keyword);

    // 尝试多个豆瓣API代理地址
    const apiUrls = [
      'https://douban.uieee.com/v2/book/search',
      'https://douban-api.uieee.com/v2/book/search',
      'https://api.douban.com/v2/book/search'
    ];

    let lastError = null;
    
    // 依次尝试多个API
    for (const apiUrl of apiUrls) {
      try {
        console.log('尝试API:', apiUrl);
        const response = await axios.get(apiUrl, {
          params: {
            q: keyword,
            count: count
          },
          timeout: 8000,
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
          }
        });

        if (response.data && response.data.books && response.data.books.length > 0) {
          console.log('成功获取到', response.data.books.length, '本图书');
          // 格式化豆瓣图书数据
          const books = response.data.books.map(book => ({
            douban_id: book.id,
            isbn: book.isbn13 || book.isbn10,
            name: book.title,
            author: book.author ? book.author.join(', ') : '',
            translator: book.translator ? book.translator.join(', ') : '',
            publisher: book.publisher,
            publish_date: book.pubdate,
            cover: book.image || book.images?.large || book.images?.medium,
            price: book.price,
            pages: book.pages,
            binding: book.binding,
            summary: book.summary,
            author_intro: book.author_intro,
            catalog: book.catalog,
            rating: book.rating?.average,
            rating_count: book.rating?.numRaters,
            data_source: 'douban'
          }));

          return success(res, books);
        }
      } catch (err) {
        console.log('API失败:', apiUrl, err.message);
        lastError = err;
        continue;
      }
    }

    // 所有API都失败了
    console.error('所有豆瓣API都无法访问');
    return error(res, '豆瓣图书API暂时无法访问，请稍后重试或使用手动添加功能', 503);
    
  } catch (err) {
    console.error('豆瓣API错误:', err.message);
    return error(res, '搜索失败，请使用手动添加图书功能', 500);
  }
};

/**
 * 根据ISBN搜索图书（简化版：仅在本地数据库查询）
 */
exports.searchByISBN = async (req, res, next) => {
  try {
    const { isbn } = req.params;
    
    if (!isbn) {
      return error(res, '请提供ISBN号', 400);
    }

    // 在本地数据库中查询
    const [books] = await pool.query(
      'SELECT * FROM books WHERE isbn = ? LIMIT 1',
      [isbn]
    );

    if (books.length > 0) {
      return success(res, books[0], '在本地数据库中找到该图书');
    } else {
      return error(res, '本地数据库中未找到该ISBN对应的图书，请手动添加', 404);
    }
  } catch (err) {
    next(err);
  }
};

/**
 * 从第三方数据导入图书到本地数据库
 */
exports.importFromExternal = async (req, res, next) => {
  try {
    const { 
      isbn, name, author, translator, publisher, publish_date, 
      category, category_id, cover, price, pages, binding, 
      summary, author_intro, catalog, stock, rating, rating_count,
      douban_id, data_source 
    } = req.body;
    
    if (!name) {
      return error(res, '书名不能为空', 400);
    }

    // 检查ISBN是否已存在
    if (isbn) {
      const [existing] = await pool.query('SELECT id FROM books WHERE isbn = ?', [isbn]);
      if (existing.length > 0) {
        return error(res, '该ISBN的图书已存在', 400);
      }
    }

    const [result] = await pool.query(
      `INSERT INTO books (isbn, name, author, translator, publisher, publish_date, 
       category, category_id, cover, price, pages, binding, summary, author_intro, 
       catalog, stock, rating, rating_count, douban_id, data_source) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [isbn, name, author, translator, publisher, publish_date, 
       category, category_id || 1, cover, price, pages, binding, 
       summary, author_intro, catalog, stock || 1, rating, rating_count,
       douban_id, data_source || 'other']
    );

    // 获取新创建的书籍信息
    const [newBooks] = await pool.query('SELECT * FROM books WHERE id = ?', [result.insertId]);

    res.status(201).send({
      code: 201,
      data: newBooks[0],
      message: '导入图书成功'
    });
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return error(res, '该图书已存在', 400);
    }
    next(err);
  }
};